/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

// 题目链接：https://leetcode.cn/problems/find-largest-value-in-each-tree-row/

class Solution
{
public:
    vector<int> largestValues(TreeNode *root)
    {
        vector<int> ret;
        if (!root)
            return ret;
        queue<TreeNode *> q; // 层序遍历的队列
        q.push(root);

        while (q.size())
        {
            int max_val = INT_MIN; // 每一层的最大值
            int sz = q.size();     // 当前层的节点个数
            while (sz--)           // 一层的处理
            {
                TreeNode *tmp = q.front();
                q.pop();
                if (tmp->val > max_val) // 更新
                    max_val = tmp->val;
                if (tmp->left)
                    q.push(tmp->left);
                if (tmp->right)
                    q.push(tmp->right);
            }
            ret.push_back(max_val);
        }
        return ret;
    }
};